﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Imaging;
using System.Runtime.InteropServices.WindowsRuntime;

namespace WeixinSB.Tools
{
    public class StorageFileEx
    {
        public static async Task SaveImage(string fileName, UIElement root) 
        {
            // 生成RenderTargetBitmap对象
            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
            await renderTargetBitmap.RenderAsync(root);
            // 获取图像的二进制数据
            var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
            // 创建程序文件存储
            IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
            IStorageFile saveFile = await applicationFolder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);
            // 把图片的二进制数据写入文件存储
            using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
                encoder.SetPixelData(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Ignore,
                    (uint)renderTargetBitmap.PixelWidth,
                    (uint)renderTargetBitmap.PixelHeight,
                    DisplayInformation.GetForCurrentView().LogicalDpi,
                    DisplayInformation.GetForCurrentView().LogicalDpi,
                    pixelBuffer.ToArray());
                await encoder.FlushAsync();
            }
        }

        public static async Task Create(string fileName, byte[] bytes)
        {
            // 获取本地文件夹根目录文件夹
            IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
            // 在文件夹里面创建文件，如果文件存在则替换掉
            IStorageFile storageFile = await applicationFolder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

            // 使用FileIO类把byte[]信息写入文件
            await FileIO.WriteBytesAsync(storageFile, bytes);
        }

        public static async void Create(string fileName, IBuffer buffer)
        {
            // 获取本地文件夹根目录文件夹
            IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
            // 在文件夹里面创建文件，如果文件存在则替换掉
            IStorageFile storageFile = await applicationFolder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

            // 使用FileIO类把IBuffer信息写入文件
            await FileIO.WriteBufferAsync(storageFile, buffer);
        }
    }
}
